//
//  SNKSettingHeaderView.m
//  SleepNews
//
//  Created by Kavee DJ on 2016/12/15.
//  Copyright © 2016年 Kavee DJ. All rights reserved.
//

#import "SNKSettingHeaderView.h"
#import <ShareSDKExtension/SSEThirdPartyLoginHelper.h>
#import <ShareSDK/ShareSDK.h>
//#import "EMSDK.h"
#import "UIImageView+WebCache.h"
#import "MBProgressHUD+Extion.h"
#import <DKNightVersion.h>
#import <AVOSCloud/AVOSCloud.h>
#import <AVOSCloudSNS.h>
#import <LeanCloudSocial/AVUser+SNS.h>

@interface SNKSettingHeaderView ()<UIAlertViewDelegate>

@property (nonatomic, weak) UIButton *logoutBtn;

@end

@implementation SNKSettingHeaderView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        // 监听三方登录的通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chooseLogin:) name:@"ThirdLogin" object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(successLogin) name:@"SuccessLogin" object:nil];
        
        // 设置header的高度,背景色
        self.frame = CGRectMake(0, 0, SCREENW, 0.6 * SCREENW);
        self.dk_backgroundColorPicker = DKColorPickerWithKey(PINK);
        self.userInteractionEnabled = YES;
        self.contentMode = UIViewContentModeScaleAspectFill;
        self.clipsToBounds = YES;
        
        // 添加注销按钮
        UIButton *logoutBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREENW - 60, 30, 50, 20)];
        [logoutBtn addTarget:self action:@selector(logoutBtnClick) forControlEvents:UIControlEventTouchUpInside];
        logoutBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [logoutBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [logoutBtn setTitle:@"注销" forState:UIControlStateNormal];
        
        // 判断是否显示注销按钮
//        NSString *loginName = [[NSUserDefaults standardUserDefaults] objectForKey:@"LOGINNAME"];
//        if (loginName.length != 0) { // 登录了，显示注销
//            logoutBtn.hidden = NO;
//        } else { // 没登录，不显示注销
//            logoutBtn.hidden = YES;
//        }
        AVUser *currentUser = [AVUser currentUser];
        if (currentUser != nil) {
            logoutBtn.hidden = NO;
        } else {
            logoutBtn.hidden = YES;
        }
        self.logoutBtn = logoutBtn;
        [self addSubview:logoutBtn];
        
        // 添加头像
        UIImageView *imageV = [[UIImageView alloc] init];
        imageV.frame = CGRectMake(self.kdj_width/2 - 40, self.kdj_height/2 - 40, 80, 80);
        imageV.image = [UIImage imageNamed:@"comment_profile_default"];
        [self addSubview:imageV];
        [imageV.layer setCornerRadius:40];
        imageV.clipsToBounds = YES;
        imageV.contentMode = UIViewContentModeScaleAspectFill;
        imageV.userInteractionEnabled = YES;
        self.photoImageV = imageV;
        
        // 添加立即登录的label
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(imageV.frame) + 10, SCREENW, 20)];
        label.textAlignment = NSTextAlignmentCenter;
        label.font = [UIFont systemFontOfSize:16];
        label.text = @"立即登录";
        label.textColor = [UIColor whiteColor];
        [self addSubview:label];
        label.userInteractionEnabled = YES;
        self.nameL = label;
        
        // 更新Profile
        [self updateProfile];
        
        
        // 添加遮盖
        UIButton *cover = [[UIButton alloc] initWithFrame:CGRectMake(self.kdj_width/2 - 40, self.kdj_height/2 - 40, 80, 110)];
        [cover addTarget:self action:@selector(countLogin) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:cover];
    }
    return self;
}

// 如果登陆了,就替换成用户的头像和昵称
- (void)updateProfile {

    AVUser *currentUser = [AVUser currentUser];
    if (currentUser != nil) { // 登录状态
        self.logoutBtn.hidden = NO;
        self.nameL.text = currentUser.username;
        
        UIImage *headImage = nil;
        // 先从沙盒中取图片
        headImage = [UIImage imageWithContentsOfFile:SNKHeadImageLocalPath];
        if (headImage == nil) { // 本地没有图片
            // 从服务器获取图片
            AVFile *headImageFile = [currentUser objectForKey:SNKUserHeadImageKey];
            NSData *headImageData = [headImageFile getData];
            headImage = [UIImage imageWithData:headImageData];
            if (headImage == nil) { // 服务器也没有，就是没有设置图片
                headImage = [UIImage imageNamed:@"comment_profile_default"];
            }else { // 服务器有图片
                self.photoImageV.image = headImage;
                
                UIImage *bgImage = [headImage imageByApplyingAlpha:0.1 image:headImage];
                bgImage = [bgImage grayscaleImageForImage:bgImage];
                
                self.image = bgImage;
            }
        } else { // 本地有图片,直接搞定
            self.photoImageV.image = headImage;
            
            UIImage *bgImage = [headImage imageByApplyingAlpha:0.1 image:headImage];
            bgImage = [bgImage grayscaleImageForImage:bgImage];
            
            self.image = bgImage;
        }
    } else { // 注销状态
        self.logoutBtn.hidden = YES;
        self.photoImageV.image = [UIImage imageNamed:@"comment_profile_default"];
        self.nameL.text = @"立即登录";
        self.image = nil;
    }
    
//    NSString *loginImage = [[NSUserDefaults standardUserDefaults] objectForKey:@"LOGINIMAGE"];
//    NSString *loginName = [[NSUserDefaults standardUserDefaults] objectForKey:@"LOGINNAME"];
//    if (loginImage.length != 0 && loginName.length != 0) {
//        KLog(@"该换头像了")
//        [self.photoImageV sd_setImageWithURL:[NSURL URLWithString:loginImage]];
//        
//        NSData *bgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:loginImage]];
//        UIImage *bgImage = [UIImage imageWithData:bgData];
//        bgImage = [bgImage imageByApplyingAlpha:0.1 image:bgImage];
//        bgImage = [bgImage grayscaleImageForImage:bgImage];
//        
//        
//        [self setImage:bgImage];
//        self.nameL.text = loginName;
//    }
//    
//    if (loginImage.length == 0 && loginName.length != 0) {
//        // 177登录了
//        self.photoImageV.image = [UIImage imageNamed:@"defaultBG.JPG"];
//        UIImage *bgImage = [UIImage imageNamed:@"defaultBG.JPG"];
//        bgImage = [bgImage imageByApplyingAlpha:0.1 image:bgImage];
//        bgImage = [bgImage grayscaleImageForImage:bgImage];
//        
//        self.image = bgImage;
//        self.nameL.text = @"Kavee DJ 🍭🍭";
//    }
}

// 用账号密码成功登录
- (void)successLogin {
//    self.photoImageV.image = [UIImage imageNamed:@"defaultBG.JPG"];
//    
//    [[NSUserDefaults standardUserDefaults] setObject:@"Kavee DJ 🍭🍭" forKey:@"LOGINNAME"];
//    
//    
//    UIImage *bgImage = [UIImage imageNamed:@"defaultBG.JPG"];
//    bgImage = [bgImage imageByApplyingAlpha:0.1 image:bgImage];
//    bgImage = [bgImage grayscaleImageForImage:bgImage];
//    
//    self.image = bgImage;
//    self.nameL.text = @"Kavee DJ 🍭🍭";
//    self.logoutBtn.hidden = NO;
    
    self.logoutBtn.hidden = NO;
    [self updateProfile];
    
}

#pragma mark - 点击遮盖,登录
- (void)countLogin
{
    if ([self.nameL.text isEqualToString:@"立即登录"]) {
        if (self.loginBlock) {
            self.loginBlock();
        }
    }else { // 已经登录了，跳转到个人信息，界面
        if (self.userDetailBlock) {
            self.userDetailBlock();
        }
    }
}

#pragma mark - 最终登录方式
- (void)chooseLogin:(NSNotification *)noti {
    
    NSString *title = noti.object;
    if ([title isEqualToString:@"QQ"]) { // QQ登录
        // 如果安装了QQ，则跳转至应用，否则跳转至网页
        [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
            KLog(@"%@", object[@"raw-user"])
            if (error) {
                NSLog(@"failed to get authentication from weibo. error: %@", error.description);
            } else {
                
                NSString *avatar = object[@"avatar"];  // 头像
                NSDictionary *rawUser = object[@"raw-user"]; // 性别等第三方平台返回的用户信息
                NSString *gender = rawUser[@"gender"]; // 性别
                NSString *city = rawUser[@"city"]; // 城市
                NSString *province = rawUser[@"province"]; // 省份
                NSString *nickname = rawUser[@"nickname"]; // 昵称
                
                city = [NSString stringWithFormat:@"%@ %@", province, city];
                
                [AVUser loginWithAuthData:object platform:AVOSCloudSNSPlatformQQ block:^(AVUser *user, NSError *error) {
                    if ([self filterError:error]) {  // 成功登录
                        [[AVUser currentUser] setObject:city forKey:@"city"];
                        [[AVUser currentUser] setObject:gender forKey:@"gender"];
                        [AVUser currentUser].username = nickname;
                        
                        //获得用户头像
                        NSData *avatatData = [NSData dataWithContentsOfURL:[NSURL URLWithString:avatar]];
                        [avatatData writeToFile:SNKHeadImageLocalPath atomically:YES];
                        
                        // ------------------更新云端
                        // 先删除云端的图片
                        AVUser *currentUser = [AVUser currentUser];
                        AVFile *preHeadImage = [currentUser objectForKey:SNKUserHeadImageKey];
                        [preHeadImage deleteInBackground];
                        // 替换为当前图片
                        AVFile *curHeadImage = [AVFile fileWithName:SNKHeadImageFullName data:avatatData];
                        [currentUser setObject:curHeadImage forKey:SNKUserHeadImageKey];
                        [currentUser saveInBackground];
                        
                        [self updateProfile];
                    }
                }];
            }
        } toPlatform:AVOSCloudSNSQQ];
        
//        [ShareSDK getUserInfo:SSDKPlatformTypeQQ onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
//            if (state == SSDKResponseStateSuccess) {
//                KLog(@"%@",user.rawData[@"figureurl_qq_2"]);
//                KLog(@"uid -- %@",user.uid);
//                KLog(@"token=%@",user.credential.token);
//                KLog(@"nickname=%@",user.nickname);
//                
//                [self.photoImageV sd_setImageWithURL:[NSURL URLWithString:user.rawData[@"figureurl_qq_2"]]];
//                self.nameL.text = user.nickname;
//                
//                [[NSUserDefaults standardUserDefaults] setObject:user.rawData[@"figureurl_qq_2"] forKey:@"LOGINIMAGE"];
//                [[NSUserDefaults standardUserDefaults] setObject:user.nickname forKey:@"LOGINNAME"];
//                [[NSUserDefaults standardUserDefaults] setObject:user.uid forKey:@"UID"];
//                
//                [self updateProfile];
//                
//                EMError *error = [[EMClient sharedClient] registerWithUsername:user.uid password:@"123"];
//                if (error==nil) {
//                    KLog(@"注册成功");
//                    //                         [MBProgressHUD showSuccess:@"注册成功"];
//                    
//                    EMError *error = [[EMClient sharedClient] loginWithUsername:user.uid password:@"123"];
//                    if (error==nil) {
//                        KLog(@"登录成功");
//                        self.logoutBtn.hidden = NO;
//                        //                             [MBProgressHUD showSuccess:@"登 录成功"];
//                        [[EMClient sharedClient].options setIsAutoLogin:YES];
//                        
//                    }else{
//                        KLog(@"登录失败,%@",error.errorDescription);
//                    }
//                    
//                }else{
//                    KLog(@"注册失败,%@",error.errorDescription);
//                    if (error.code == EMErrorUserAlreadyExist){
//                        
//                        EMError *error = [[EMClient sharedClient] loginWithUsername:user.uid password:@"123"];
//                        if (error==nil) {
//                            KLog(@"登录成功");
//                            self.logoutBtn.hidden = NO;
//                            //                             [MBProgressHUD showSuccess:@"登录成功"];
//                            [[EMClient sharedClient].options setIsAutoLogin:YES];
//                            
//                        }else{
//                            KLog(@"登录失败,%@",error.errorDescription);
//                        }
//                    }
//                }
//                
//            } else {
//                [MBProgressHUD showError:@"登录失败"];
//            }
//        }];
        
    }else if ([title isEqualToString:@"微信"]){ // warning 微信登录-----待实现
        if ([AVOSCloudSNS isAppInstalledForType:AVOSCloudSNSWeiXin]) {
            // 请到真机测试
            [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
                if ([self filterError:error]) {
                    [AVUser loginWithAuthData:object platform:AVOSCloudSNSPlatformWeiXin block:^(AVUser *user, NSError *error) {
                        if ([self filterError:error]) {
                            [self updateProfile];
                        }
                    }];
                }
            } toPlatform:AVOSCloudSNSWeiXin];
        } else {
            [self alert:@"没有安装微信，暂不能登录"];
        }
        

    }else { // 微博登录
        // 如果安装了微博，直接跳转到微博应用，否则跳转至网页登录
        [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
            KLog(@"%@", object[@"raw-user"])
            if (error) {
                NSLog(@"failed to get authentication from weibo. error: %@", error.description);
            } else {
                NSDictionary *rawUser = object[@"raw-user"]; // 性别等第三方平台返回的用户信息
                NSString *avatar = object[@"avatar"];  // 头像
                NSString *nickname = rawUser[@"name"]; // 昵称
                NSString *location = rawUser[@"location"];  // 位置
                NSString *gender = rawUser[@"gender"];  // 性别 m f
                gender = [gender isEqualToString:@"m"]?@"男":@"女";
                
                [AVUser loginWithAuthData:object platform:AVOSCloudSNSPlatformWeiBo block:^(AVUser *user, NSError *error) {
                    if ([self filterError:error]) {
                        [[AVUser currentUser] setObject:location forKey:@"city"];
                        [[AVUser currentUser] setObject:gender forKey:@"gender"];
                        [AVUser currentUser].username = nickname;
                        
                        //获得用户头像
                        NSData *avatatData = [NSData dataWithContentsOfURL:[NSURL URLWithString:avatar]];
                        [avatatData writeToFile:SNKHeadImageLocalPath atomically:YES];
                        
                        // ------------------更新云端
                        // 先删除云端的图片
                        AVUser *currentUser = [AVUser currentUser];
                        AVFile *preHeadImage = [currentUser objectForKey:SNKUserHeadImageKey];
                        [preHeadImage deleteInBackground];
                        // 替换为当前图片
                        AVFile *curHeadImage = [AVFile fileWithName:SNKHeadImageFullName data:avatatData];
                        [currentUser setObject:curHeadImage forKey:SNKUserHeadImageKey];
                        [currentUser saveInBackground];
                        
                        [self updateProfile];
                    }
                }];
            }
        } toPlatform:AVOSCloudSNSSinaWeibo];
                
//                NSString *accessToken = object[@"access_token"];
//                NSString *username = object[@"username"];
//                NSString *avatar = object[@"avatar"];
//                NSDictionary *rawUser = object[@"raw-user"]; // 性别等第三方平台返回的用户信息
//
//        [ShareSDK getUserInfo:SSDKPlatformTypeSinaWeibo
//               onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error) {
//                   
//             if (state == SSDKResponseStateSuccess) {
//
//                 
//                 KLog(@"%@",user)
//                 
//                 KLog(@"uid --- %@",user.uid);
//                 KLog(@"%@",user.icon);
//                 KLog(@"nickname=%@",user.nickname);
//
//                 [self.photoImageV sd_setImageWithURL:[NSURL URLWithString:user.icon]];
//                 self.nameL.text = user.nickname;
//
//                 [[NSUserDefaults standardUserDefaults] setObject:user.icon forKey:@"LOGINIMAGE"];
//                 [[NSUserDefaults standardUserDefaults] setObject:user.nickname forKey:@"LOGINNAME"];
//                 [[NSUserDefaults standardUserDefaults] setObject:user.uid forKey:@"UID"];
//
//                 [self updateProfile];
//
//                 EMError *error = [[EMClient sharedClient] registerWithUsername:user.uid password:@"123"];
//                 if (error==nil) {
//                     KLog(@"注册成功");
//                     //                         [MBProgressHUD showSuccess:@"注册成功"];
//
//                     EMError *error = [[EMClient sharedClient] loginWithUsername:user.uid password:@"123"];
//                     if (error==nil) {
//                         KLog(@"登录成功");
//                         self.logoutBtn.hidden = NO;
//                         //                             [MBProgressHUD showSuccess:@"登录成功"];
//                         [[EMClient sharedClient].options setIsAutoLogin:YES];
//
//                     }else{
//                         KLog(@"登录失败,%@",error.errorDescription);
//                     }
//
//                 }else{
//                     KLog(@"注册失败,%@",error.errorDescription);
//                     if (error.code == EMErrorUserAlreadyExist){
//
//                         EMError *error = [[EMClient sharedClient] loginWithUsername:user.uid password:@"123"];
//                         if (error==nil) {
//                             KLog(@"登录成功");
//                             self.logoutBtn.hidden = NO;
//                             //                             [MBProgressHUD showSuccess:@"登录成功"];
//                             [[EMClient sharedClient].options setIsAutoLogin:YES];
//
//                         }else{
//                             KLog(@"登录失败,%@",error.errorDescription);
//                         }
//                     }
//                 }
//
//             }else{
//                 [MBProgressHUD showError:@"登录失败"];
//             }
//         }];
        
    }
}


#pragma mark - 取消授权 退出
- (void)logoutBtnClick {
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确定要注销吗" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [AVUser logOut];
        [self updateProfile];
        [MBProgressHUD showSuccess:@"注销成功"];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)alert:(NSString *)message {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:message delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [alert show];
}

- (BOOL)filterError:(NSError *)error {
    if (error) {
        [self alert:[error localizedDescription]];
        return NO;
    }
    return YES;
}

@end
